<template>
  <div class="event-page">
    <!-- 顶部统计卡片 -->
    <el-row :gutter="20" class="mb-6">
      <el-col :span="6" v-for="stat in statistics" :key="stat.title">
        <el-card class="stat-card" :class="stat.type">
          <div class="stat-content">
            <div class="stat-icon">
              <el-icon :size="24"><component :is="stat.icon" /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ stat.value }}</div>
              <div class="stat-title">{{ stat.title }}</div>
            </div>
          </div>
          <div class="stat-trend">
            <span :class="stat.trend >= 0 ? 'up' : 'down'">
              {{ Math.abs(stat.trend) }}%
              <el-icon>
                <CaretTop v-if="stat.trend >= 0" />
                <CaretBottom v-else />
              </el-icon>
            </span>
            较上周
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 图表和筛选区域 -->
    <el-row :gutter="20" class="mb-6">
      <el-col :span="16">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span class="font-medium">异常趋势分析</span>
              <el-radio-group v-model="chartTimeRange" size="small">
                <el-radio-button label="week">本周</el-radio-button>
                <el-radio-button label="month">本月</el-radio-button>
                <el-radio-button label="year">全年</el-radio-button>
              </el-radio-group>
            </div>
          </template>
          <div ref="trendChartRef" style="height: 350px"></div>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span class="font-medium">异常类型分布</span>
            </div>
          </template>
          <div ref="pieChartRef" style="height: 350px"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 事件列表 -->
    <el-card class="event-list-card">
      <template #header>
        <div class="list-header">
          <div class="header-left">
            <span class="font-medium">异常事件列表</span>
            <el-tag type="danger" class="ml-2">{{ totalEvents }} 条记录</el-tag>
          </div>
          <div class="header-right">
            <el-button type="primary" @click="showAddDialog">
              <el-icon><Plus /></el-icon>记录异常
            </el-button>
            <el-button @click="exportEvents">
              <el-icon><Download /></el-icon>导出
            </el-button>
          </div>
        </div>
      </template>

      <!-- 筛选表单 -->
      <el-form :model="filterForm" class="filter-form" inline>
        <el-form-item label="时间范围">
          <el-date-picker
            v-model="filterForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          />
        </el-form-item>
        <el-form-item label="异常等级">
          <el-select
            v-model="filterForm.level"
            placeholder="选择等级"
            clearable
          >
            <el-option
              v-for="item in levelOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="处理状态">
          <el-select
            v-model="filterForm.status"
            placeholder="选择状态"
            clearable
          >
            <el-option
              v-for="item in statusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleFilter">筛选</el-button>
          <el-button @click="resetFilter">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 表格 -->
      <el-table
        :data="eventList"
        style="width: 100%"
        :border="true"
        v-loading="loading"
      >
        <el-table-column prop="id" label="事件ID" width="100" />
        <el-table-column prop="timestamp" label="发生时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.timestamp) }}
          </template>
        </el-table-column>
        <el-table-column prop="type" label="异常类型" width="120" />
        <el-table-column prop="level" label="等级" width="100">
          <template #default="{ row }">
            <el-tag :type="getLevelTag(row.level)">{{ row.level }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="描述" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusTag(row.status)">{{ row.status }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="{ row }">
            <el-button link type="primary" @click="handleEdit(row)">
              编辑
            </el-button>
            <el-button link type="primary" @click="handleDetail(row)">
              详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="totalEvents"
          layout="total, sizes, prev, pager, next"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '记录异常事件' : '编辑异常事件'"
      width="600px"
    >
      <el-form
        ref="eventFormRef"
        :model="eventForm"
        :rules="eventRules"
        label-width="100px"
      >
        <el-form-item label="异常类型" prop="type">
          <el-select v-model="eventForm.type" placeholder="选择异常类型">
            <el-option
              v-for="item in typeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="异常等级" prop="level">
          <el-select v-model="eventForm.level" placeholder="选择异常等级">
            <el-option
              v-for="item in levelOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="发生时间" prop="timestamp">
          <el-date-picker
            v-model="eventForm.timestamp"
            type="datetime"
            placeholder="选择时间"
          />
        </el-form-item>
        <el-form-item label="异常描述" prop="description">
          <el-input
            v-model="eventForm.description"
            type="textarea"
            rows="3"
            placeholder="请输入异常描述"
          />
        </el-form-item>
        <el-form-item label="处理状态" prop="status">
          <el-select v-model="eventForm.status" placeholder="选择处理状态">
            <el-option
              v-for="item in statusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import * as echarts from 'echarts'
// 统计数据
const statistics = ref([
  {
    title: '今日异常',
    value: 28,
    trend: 12.5,
    type: 'danger',
    icon: 'Warning'
  },
  {
    title: '待处理',
    value: 15,
    trend: -5.2,
    type: 'warning',
    icon: 'Timer'
  },
  {
    title: '已解决',
    value: 156,
    trend: 8.4,
    type: 'success',
    icon: 'CircleCheck'
  },
  {
    title: '解决率',
    value: '91.2%',
    trend: 2.1,
    type: 'info',
    icon: 'DataLine'
  }
])

// 图表相关
const chartTimeRange = ref('week')
const trendChartRef = ref(null)
const pieChartRef = ref(null)
let trendChart = null
let pieChart = null

// 列表相关
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const totalEvents = ref(0)
const eventList = ref([])

// 筛选表单
const filterForm = ref({
  dateRange: [],
  level: '',
  status: ''
})

// 新增/编辑表单
const dialogVisible = ref(false)
const dialogType = ref('add')
const eventFormRef = ref(null)
const eventForm = ref({
  type: '',
  level: '',
  timestamp: '',
  description: '',
  status: ''
})

// 选项
const levelOptions = [
  { value: 'critical', label: '严重' },
  { value: 'major', label: '重要' },
  { value: 'minor', label: '次要' }
]

const statusOptions = [
  { value: 'pending', label: '待处理' },
  { value: 'processing', label: '处理中' },
  { value: 'resolved', label: '已解决' }
]

const typeOptions = [
  { value: 'system', label: '系统异常' },
  { value: 'network', label: '网络异常' },
  { value: 'device', label: '设备异常' },
  { value: 'security', label: '安全异常' }
]

// 表单验证规则
const eventRules = {
  type: [{ required: true, message: '请选择异常类型', trigger: 'change' }],
  level: [{ required: true, message: '请选择异常等级', trigger: 'change' }],
  timestamp: [{ required: true, message: '请选择发生时间', trigger: 'change' }],
  description: [{ required: true, message: '请输入异常描述', trigger: 'blur' }],
  status: [{ required: true, message: '请选择处理状态', trigger: 'change' }]
}

// 初始化图表
const initCharts = () => {
  // 趋势图表
  if (trendChartRef.value) {
    trendChart = echarts.init(trendChartRef.value)
    const trendOption = {
      color: ['#4834d4'],
      tooltip: {
        trigger: 'axis'
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
      },
      yAxis: {
        type: 'value'
      },
      series: [
        {
          data: [30, 25, 35, 45, 35, 40, 42],
          type: 'line',
          smooth: true,
          areaStyle: {
            opacity: 0.1
          }
        }
      ]
    }
    trendChart.setOption(trendOption)
  }

  // 饼图
  if (pieChartRef.value) {
    pieChart = echarts.init(pieChartRef.value)
    const pieOption = {
      color: ['#4834d4', '#686de0', '#9c88ff', '#c7c1ff'],
      tooltip: {
        trigger: 'item'
      },
      legend: {
        orient: 'vertical',
        right: 10,
        top: 'center'
      },
      series: [
        {
          name: '异常类型',
          type: 'pie',
          radius: ['40%', '70%'],
          center: ['40%', '50%'],
          avoidLabelOverlap: false,
          itemStyle: {
            borderRadius: 10,
            borderColor: '#fff',
            borderWidth: 2
          },
          label: {
            show: false
          },
          emphasis: {
            label: {
              show: true,
              fontSize: 14,
              fontWeight: 'bold'
            }
          },
          labelLine: {
            show: false
          },
          data: [
            { value: 35, name: '系统异常' },
            { value: 30, name: '网络异常' },
            { value: 24, name: '设备异常' },
            { value: 11, name: '安全异常' }
          ]
        }
      ]
    }
    pieChart.setOption(pieOption)
  }
}

// 页面方法
const handleFilter = () => {
  loading.value = true
  // 模拟API调用
  setTimeout(() => {
    loading.value = false
    ElMessage.success('筛选成功')
  }, 500)
}

const resetFilter = () => {
  filterForm.value = {
    dateRange: [],
    level: '',
    status: ''
  }
  handleFilter()
}

const showAddDialog = () => {
  dialogType.value = 'add'
  eventForm.value = {
    type: '',
    level: '',
    timestamp: new Date(),
    description: '',
    status: 'pending'
  }
  dialogVisible.value = true
}

const handleEdit = (row) => {
  dialogType.value = 'edit'
  eventForm.value = { ...row }
  dialogVisible.value = true
}

const handleDetail = (row) => {
  ElMessage.info(`查看详情：${row.id}`)
}

const handleSubmit = async () => {
  if (!eventFormRef.value) return

  await eventFormRef.value.validate((valid) => {
    if (valid) {
      // 模拟API调用
      loading.value = true
      setTimeout(() => {
        loading.value = false
        dialogVisible.value = false
        ElMessage.success(dialogType.value === 'add' ? '添加成功' : '更新成功')
        fetchEventList()
      }, 500)
    }
  })
}

const handleSizeChange = (val) => {
  pageSize.value = val
  fetchEventList()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchEventList()
}

// 获取事件列表
const fetchEventList = () => {
  loading.value = true
  // 模拟API调用
  setTimeout(() => {
    eventList.value = [
      {
        id: '1001',
        timestamp: new Date(),
        type: '系统异常',
        level: 'critical',
        description: 'CPU使用率异常飙升至95%',
        status: 'pending'
      }
      // ... 更多模拟数据
    ]
    totalEvents.value = 100
    loading.value = false
  }, 500)
}

// 工具方法
const formatDate = (date) => {
  return new Date(date).toLocaleString()
}

const getLevelTag = (level) => {
  const map = {
    critical: 'danger',
    major: 'warning',
    minor: 'info'
  }
  return map[level] || 'info'
}

const getStatusTag = (status) => {
  const map = {
    pending: 'danger',
    processing: 'warning',
    resolved: 'success'
  }
  return map[status] || 'info'
}

// 生命周期钩子
onMounted(() => {
  fetchEventList()
  nextTick(() => {
    initCharts()
    window.addEventListener('resize', () => {
      trendChart?.resize()
      pieChart?.resize()
    })
  })
})
</script>

<style lang="scss" scoped>
.event-page {
  padding: 20px;

  .mb-6 {
    margin-bottom: 24px;
  }

  .stat-card {
    background: #fff;
    border-radius: 8px;

    &.danger {
      .stat-icon {
        color: #ff4757;
      }
    }
    &.warning {
      .stat-icon {
        color: #ffa502;
      }
    }
    &.success {
      .stat-icon {
        color: #2ed573;
      }
    }
    &.info {
      .stat-icon {
        color: #4834d4;
      }
    }

    .stat-content {
      display: flex;
      align-items: center;
      margin-bottom: 12px;

      .stat-icon {
        width: 48px;
        height: 48px;
        border-radius: 8px;
        background: rgba(72, 52, 212, 0.1);
        display: flex;
        align-items: center;
        justify-content: center;
        margin-right: 12px;
      }

      .stat-info {
        .stat-value {
          font-size: 24px;
          font-weight: 600;
          line-height: 1.2;
          color: #2d3436;
        }

        .stat-title {
          font-size: 14px;
          color: #636e72;
        }
      }
    }

    .stat-trend {
      font-size: 12px;
      color: #636e72;

      span {
        &.up {
          color: #2ed573;
        }
        &.down {
          color: #ff4757;
        }
      }
    }
  }

  .chart-card {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
  }

  .event-list-card {
    .list-header {
      display: flex;
      justify-content: space-between;
      align-items: center;

      .header-left {
        display: flex;
        align-items: center;
      }
    }

    .filter-form {
      margin-bottom: 20px;
      padding: 16px;
      background: #f8f9fa;
      border-radius: 8px;
    }
  }

  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
}

:deep(.el-card__header) {
  padding: 16px 20px;
  border-bottom: 1px solid #ebeef5;
}

:deep(.el-table) {
  border-radius: 8px;
  overflow: hidden;
}
</style>
